import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'
import { resolve } from 'path'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const isProd = mode === 'production'
  
  return {
    plugins: [
      react(),
      // 生产环境启用 Gzip 压缩
      isProd && viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240, // 大于 10kb 的文件才会被压缩
        algorithm: 'gzip',
        ext: '.gz',
        deleteOriginFile: false, // 保留原始文件
      }),
      // 生产环境启用 Brotli 压缩 (更高压缩比)
      isProd && viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'brotliCompress',
        ext: '.br',
        deleteOriginFile: false,
      }),
      // 打包体积分析
      isProd && visualizer({
        filename: 'dist/stats.html',
        open: false,
        gzipSize: true,
        brotliSize: true,
      }),
    ].filter(Boolean),
    
    // 环境变量配置
    define: {
      __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
      // 移除生产环境的 console 和 debugger
      ...(isProd && {
        'process.env.NODE_ENV': JSON.stringify('production'),
      }),
    },
    
    // 开发服务器配置
    server: {
      port: 8000, // 修改端口避免冲突
      // open: true,
      proxy: {
        // API 代理
        '/api': {
          target: 'http://113.44.139.133:8000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    
    // 构建配置
    build: {
      outDir: 'dist',
      sourcemap: mode === 'development',
      // 清理构建目录
      emptyOutDir: true,
      // CSS 代码分割
      cssCodeSplit: true,
      // 启用 Terser 压缩
      minify: 'terser',
      terserOptions: {
        compress: {
          // 移除 console 和 debugger
          drop_console: isProd,
          drop_debugger: isProd,
        },
      },
      // 设置 chunk 大小警告阈值
      chunkSizeWarningLimit: 1000,
      rollupOptions: {
        output: {
          // 静态资源分类打包
          assetFileNames: (assetInfo) => {
            const fileName = assetInfo.name || 'unknown';
             
            if (/\.(png|jpe?g|gif|svg|webp|ico)$/.test(fileName)) {
              return `static/img/[name].[hash].[ext]`;
            }
             
            if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)$/.test(fileName)) {
              return `static/media/[name].[hash].[ext]`;
            }
             
            if (/\.(woff2?|eot|ttf|otf)$/.test(fileName)) {
              return `static/fonts/[name].[hash].[ext]`;
            }
             
            if (/\.css$/.test(fileName)) {
              return `static/css/[name].[hash].[ext]`;
            }
             
            if (/\.(glb|gltf)$/.test(fileName)) {
              return `static/glb/[name].[hash].[ext]`;
            }
             
            return `static/other/[name].[hash].[ext]`;
          },
          // JS 文件输出目录
          chunkFileNames: 'static/js/[name].[hash].js',
          entryFileNames: 'static/js/[name].[hash].js',
          // 更精细的代码分割策略
          manualChunks: (id) => {
            // React 相关库
            if (id.includes('node_modules/react') || 
                id.includes('node_modules/react-dom') || 
                id.includes('node_modules/scheduler')) {
              return 'react-vendor';
            }
            
            // Three.js 相关库
            if (id.includes('node_modules/three') || 
                id.includes('node_modules/@react-three')) {
              return 'three-vendor';
            }
            // Antd UI 库
            if (id.includes('node_modules/antd') || 
                id.includes('node_modules/@ant-design')) {
              return 'antd-vendor';
            }
            // 其他常用库
            if (id.includes('node_modules/axios') || 
                id.includes('node_modules/redux') || 
                id.includes('node_modules/@reduxjs')) {
              return 'utils-vendor';
            }
            // 按页面分包
            if (id.includes('/src/page/')) {
              const pageName = id.split('/src/page/')[1].split('/')[0];
              return `page-${pageName}`;
            }
            // 按组件分包
            if (id.includes('/src/Components/')) {
              const componentName = id.split('/src/Components/')[1].split('/')[0];
              return `component-${componentName}`;
            }
            // 其他第三方库
            if (id.includes('node_modules/')) {
              return 'vendors';
            }
          },
        },
        // 外部化处理（如果需要 CDN）
        // external: ['react', 'react-dom'],
        // Tree-shaking 优化
        treeshake: {
          preset: 'recommended',
          manualPureFunctions: ['console.log', 'console.info'],
        },
      },
    },
    // 优化配置
    optimizeDeps: {
      // 预构建包含的依赖
      include: [
        'react',
        'react-dom',
        'react-router-dom',
        'antd',
        'axios',
        '@ant-design/icons',
        'three',
        '@react-three/fiber',
        '@react-three/drei',
      ],
      // 排除预构建的依赖
      exclude: ['@vite/client', '@vite/env'],
    },
    // 环境变量前缀
    envPrefix: 'VITE_',
    // 解析配置
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
  }
})
